package com.liu.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class FileController {
    //@RequestParam("file")将name=file控件得到的文件封装成CommonsMultipartFile对象
    //批量上传CommonsMultipartFile则为数组即可
    @RequestMapping("/upload")
    public String fileUpload(CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//    获取文件名：file.getOriginalFilename
        String originalFilename = file.getOriginalFilename();
//        如果文件名为空，直接返回首页
        if("".equals(originalFilename)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名："+originalFilename);
//        上传路径保存设置
        String path=request.getServletContext().getRealPath("/upload");
//        如果路径不存在，创建一个
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdir();
        }
        System.out.println("上传文件保存地址："+file1);
        InputStream inputStream = file.getInputStream();//文件输入流
        FileOutputStream fileOutputStream = new FileOutputStream(new File(file1, originalFilename));//文件输出流
//        读取写出
        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=inputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,len);
                fileOutputStream.flush();
        }
        fileOutputStream.close();
        inputStream.close();
        return "redirect:index,jsp";


    }
    public String fileUpload2(CommonsMultipartFile file,HttpServletRequest request) throws IOException {
//上传保存路径
        String realPath = request.getServletContext().getRealPath("/upload");
        File file1 = new File(realPath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址"+file1);
//        通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(file1+"/"+file.getOriginalFilename()));
        return "redirect:/index.jsp";
    }
}
